package com.usermanage.controller;

import com.usermanage.SecurityConfig.SpringSecurityUtils;
import com.usermanage.SecurityConfig.UserDetail;
import com.usermanage.Service.GroupMemberService;
import com.usermanage.Service.GroupPermissionService;
import com.usermanage.Service.PermissionService;
import com.usermanage.beanParam.GroupPermissionBean;
import com.usermanage.beanParam.PermissionBean;
import com.usermanage.util.JsonData;
import com.usermanage.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;

/**
 * 权限接口
 * searchRoleByGroup   根据用户组id查询用户权限列表
 *addGroupRole 根据组织id添加组织权限
 * addRole  添加权限详情，超级管理员添加
 */
@Slf4j
@Api(description = "权限接口")
@RestController
@RequestMapping("/permission")
public class PermissionController {

    @Resource
    private PermissionService permissionService;
    @Resource
    private GroupPermissionService groupPermissionService;
    @Resource
    private GroupMemberService groupMemberService;


    /**
     *当pid不为空时根据组id得到组下的子树列表用于首页左边菜单栏    当id为空时查出所有权限树列表
     * @param pid
     * @return
     * @throws Exception
     */
    @RequestMapping("/permissionTreeList.json")
    public JsonData getPermissionListByPermissionId(String pid) throws Exception{
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
//        StringBuffer buffer = new StringBuffer();
//        List<Integer> list = groupMemberService.findUserGroup(String.valueOf(userDetail.getId()), userDetail.getCompany_id());
//        for (int i = 0; i < list.size(); i++) {
//            buffer.append(list.get(i)).append(",");
//        }
        List<PermissionBean> pList = permissionService.findPermissionNewByGroupId(null);


        if(StringUtils.isNotBlank(pid)){
            //pid不为空表示根据id查询出下级列表主要用于菜单栏列表展示
            List<PermissionBean> result = new ArrayList<>();
            //从树列表中根据id查询到该组下的子树列表
            for (int i = 0; i < pList.size(); i++) {
                PermissionBean abc = pList.get(i);
                if (pid.equals(abc.getId().toString())){
                    result = abc.getChildren();
                }
            }
            return JsonData.success(result);
        }else{
            //pid为空表示查询出所有的权限树列表
            return JsonData.success(pList);
        }
    }


    /**
     * 得到组织下拥有的所有权限（超级管理员）
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/permissionTreeList.page",method= RequestMethod.GET)
    public ModelAndView permissionTreeList()throws Exception{
        ModelAndView mv = new ModelAndView();
        String groupId = SpringSecurityUtils.getCurrentUser().getGroup_id();
        List<PermissionBean> list = permissionService.findAllPermissionByGroupId(groupId);
        mv.addObject("add","fail");
        mv.addObject("update","fail");
        //获得用户登陆信息
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        //从用户登陆信息中获取用户权限列表
        List<PermissionBean> permissionBeanList = userDetail.getList();
        //判断用户具有的权限在界面展示
        for (PermissionBean bean:permissionBeanList) {
            if (bean.getPermission_url().equals("/permission/permissionTreeListAdd.json")){
                mv.addObject("add","success");
            }else if(bean.getPermission_url().equals("/permission/permissionTreeListUpdate.json")){
                mv.addObject("update","success");
            }
        }
        mv.addObject("list",StringUtil.ObjectToJson(list));
        mv.setViewName("/permission/list");
        return mv;
    }



    /**
     * ajax得到组织下拥有的所有权限树列表（超级管理员）
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/permissionTreeJsonList.json",method= RequestMethod.POST)
    public JsonData permissionTreeJsonList()throws Exception{
        String groupId = SpringSecurityUtils.getCurrentUser().getGroup_id();
        List<PermissionBean> list = permissionService.findAllPermissionByGroupId(groupId);
        return JsonData.success(list);
    }


    /**
     * 添加权限详情，超级管理员添加
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "添加权限信息",notes="添加权限信息")
    @RequestMapping(value="/operaPermission.json",method= RequestMethod.POST,produces = "application/json;charset=utf-8")
    public JsonData creatPermission(@Valid PermissionBean bean, BindingResult bindingResult)throws Exception{
        try {
            //验证提交参数
            if(bindingResult.hasErrors()){
                return JsonData.fail(bindingResult.getFieldError().getDefaultMessage());
            }
            UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
            if(bean.getId() != null && bean.getId()>0){//id存在表示需要修改
                Optional<PermissionBean> optional = permissionService.findById(bean.getId());
                if (optional.isPresent()){//父级组查询成功
                    PermissionBean permissionBean = optional.get();
                    permissionBean.setPermission_name(bean.getPermission_name());
                    permissionBean.setPermission_url(bean.getPermission_url());
                    bean = permissionBean;
                }else{
                    return JsonData.fail("修改数据异常！");
                }
                //修改权限
                permissionService.save(bean);
            }else{//id不存在表示是添加
                int parentId = Integer.valueOf(bean.getParent_id());
                //验证部门是否存在
                boolean bool =permissionService.isExist(bean.getPermission_name(),bean.getPermission_url(),bean.getParent_id());
                if(bool) {
                    return JsonData.fail("同级下不能存在相同操作");
                }
                //链接为空表示添加一级目录，设置初始的参数
                if (StringUtils.isBlank(bean.getPermission_url())){
                    bean.setParent_id("0");
                    bean.setPermission_url("#");
                    bean.setLevel("0");
                }else{
                    //url不为空的时候计算level
                    Optional<PermissionBean> optional = permissionService.findById(parentId);
                    if (optional.isPresent()){//父级组查询成功
                        bean.setLevel(StringUtil.calculateLevel(optional.get().getLevel(), parentId));
                    }else{
                        bean.setLevel(StringUtil.calculateLevel(null, parentId));
                    }
                }
                bean.setCreat_time(new Date());
                bean.setSeq("1");
                bean.setGroup_id(userDetail.getGroup_id());
                //保存权限
                PermissionBean permissionBean = permissionService.save(bean);
                //默认吧该权限赋给超级管理员
                GroupPermissionBean groupPermissionBean = new GroupPermissionBean();
                groupPermissionBean.setPermission_id(String.valueOf(permissionBean.getId()));
                groupPermissionBean.setGroup_id(userDetail.getGroup_id());
                groupPermissionService.save(groupPermissionBean);
            }


            return JsonData.success(bean.getId());
        }catch (Exception e){
            //打印日志
            return JsonData.fail("系统异常！");
        }
    }



















    /**
     * 根据组id查询用户权限列表
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "根据用户信息查询用户权限列表",notes="根据用户信息查询用户权限列表")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "groupId", value = "用户组id", required = true,  paramType = "query", dataType = "String")
//    })
    @RequestMapping(value="/searchRoleByGroup",method= RequestMethod.GET)
    public JsonData searchRoleByGroup()throws Exception{
        String groupId = SpringSecurityUtils.getCurrentUser().getGroup_id();
        List<PermissionBean> list = permissionService.findPermissionByGroupId(groupId);
//        List<PermissionBean> result = groupListToTree(list);
        return JsonData.success();
    }






    @ApiOperation(value = "根据用户id，操作url，操作名称判断该权限是否存在" ,  notes="根据用户id，操作url，操作名称判断该权限是否存在")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "url", value = "url链接", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "operationName", value = "操作名称", required = true, paramType = "query", dataType = "String"),
    })
    @RequestMapping(value="/checkRole",method= RequestMethod.GET)
    public JsonData checkRole(@RequestParam("url") String url,@RequestParam("operationName") String operationName){
        //从用户登陆信息中取到用户id
//        String userId = SpringSecurityUtils.getCurrentUserId();
        String groupId = null;
//        if (StringUtils.isBlank(userId)){
//            return JsonData.success("用户没有登陆，请登陆！");
//        }
//        //1、根据用户id,url路径，操作名判断用户是否具有该权限。
//        boolean bool = roleService.checkRole(groupId,url);
//        if (bool){//表示没有操作权限
//            return JsonData.fail("您没有该操作权限，请联系管理员。");
//        }
        return JsonData.success();
    }



    /**
     * 根据组织id添加组织权限
     * @return permissionId   组下选中权限列表
     * @return groupId  组id   
     * @throws Exception
     */
    @ApiOperation(value = "根据组织id添加组织权限",notes="根据组织id添加组织权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "permissionId", value = "选中组权限", required = true,  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "groupId", value = "组id", required = true,  paramType = "query", dataType = "String")
    })
    @RequestMapping(value="/addGroupRole",method= RequestMethod.POST)
    public JsonData addGroupRole(@RequestParam("permissionId") String permissionId,@RequestParam("groupId") String groupId)throws Exception{
        try {
            //1、验证该权限组下是否存在该权限，true:表示已存在，false:表示不存在
//            boolean bool = groupPermissionService.isExsit(permissionId,groupId);
//            if (bool){
//                return JsonData.fail("已拥有该权限");
//            }
//        //2、根据权限id和权限组id为该权限组添加一个权限
            GroupPermissionBean bean = new GroupPermissionBean();
            bean.setGroup_id(groupId);
            bean.setPermission_id(permissionId);
            groupPermissionService.save(bean);
        }catch (Exception e){
            log.error("组权限添加异常。");
            return JsonData.fail("系统异常！");
        }
        return JsonData.success();
    }

}
